<template>
  <div class="contentbox flex-col">
    <el-card class="card-margin flex-col">
      <el-descriptions
        title="采集任务信息"
        size="medium"
        :column="1"
        :colon="false"
      >
        <el-descriptions-item>
          <div class="taskview-top">
            <span>工厂：</span>
            <el-select placeholder="请选择" v-model="lineName" clearable>
              <el-option
                v-for="item in lineType"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <span>工序：</span>
            <el-select placeholder="请选择" v-model="processName" clearable>
              <el-option
                v-for="item in processType"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <span>设备：</span>
            <el-input placeholder="请输入检索" v-model="eqSearchName">
            </el-input>
            <span>任务分类：</span>
            <el-select placeholder="请选择" v-model="rule">
              <el-option
                v-for="item in ruleType"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <span>任务名称：</span>
            <el-input placeholder="请输入检索" v-model="scriptName"> </el-input>
            <span>状态：</span>
            <el-select placeholder="请选择" v-model="state">
              <el-option
                v-for="item in stateType"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              >
              </el-option
            ></el-select>
            <el-button type="primary" @click="getTaskHistory">搜索</el-button>
            <el-button type="warning" @click="handleStateListChange('取消执行')"
              >取消执行</el-button
            >
            <el-button type="warning" @click="handleStateListChange('启动执行')"
              >启动执行</el-button
            >
            <!-- <el-button type="warning">取消执行</el-button>
            <el-button type="warning">启动执行</el-button> -->
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <div class="taskmain flex-col">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          tooltip-effect="dark"
          height="100%"
          @selection-change="handleSelectionChange"
          @sort-change="handleSort"
        >
          >
          <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
          <el-table-column type="selection"> </el-table-column>
          <el-table-column type="index" label="序号" :index="table_index">
          </el-table-column>
          <el-table-column label="任务ID">
            <template slot-scope="scope">
              <span>{{ `${scope.row.scriptContentId}` }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="lineName" label="工厂"> </el-table-column>
          <el-table-column prop="processName" label="工序"> </el-table-column>
          <el-table-column prop="eqName" label="设备"> </el-table-column>
          <el-table-column label="任务分类">
            <template slot-scope="scope">
              <span>
                {{
                  ruleType.find((v) => v.value === scope.row.ruleType)?.name ||
                  ""
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="scriptName" label="任务名称">
          </el-table-column>
          <el-table-column prop="version" label="版本号"> </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <span>
                {{
                  stateType.find((v) => v.value === scope.row.scriptStatus)
                    ?.name || ""
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            sortable="custom"
            prop="createTime"
            label="任务创建时间"
          >
          </el-table-column>
          <el-table-column prop="executeTime" label="任务最近执行时间">
          </el-table-column>
          <!-- <el-table-column prop="address" label="任务最近执行时间">
          </el-table-column> -->
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleEdit(scope.$index, scope.row)"
                >任务详情</el-button
              >
              <template
                v-if="
                  stateType.find((v) => v.value === scope.row.scriptStatus)
                    ?.name != '结束'
                "
              >
                <el-button
                  type="text"
                  @click="
                    handleSingleStateChange(
                      scope.$index,
                      scope.row,
                      stateType.find((v) => v.value === scope.row.scriptStatus)
                        ?.name == '生效'
                        ? '取消执行'
                        : '启动执行'
                    )
                  "
                >
                  {{
                    stateType.find((v) => v.value === scope.row.scriptStatus)
                      ?.name == "生效"
                      ? "取消执行"
                      : "启动执行"
                  }}
                </el-button>
                <el-button
                  type="text"
                  @click="handleLogSearch(scope.$index, scope.row)"
                  >日志查询</el-button
                >
              </template>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="->,total,sizes,prev, pager, next,jumper"
          :total="total"
          :current-page.sync="pageNum"
          :page-sizes="[20, 40, 60, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog :visible.sync="triggerVisible" width="30%">
      <span slot="title" style="text-align: center"
        >脚本详情
        <el-divider></el-divider>
      </span>

      <codemirror
        style="height: 600px"
        v-model="scriptContent"
        :options="cmOptions"
      ></codemirror>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-divider></el-divider>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// #region 覆盖scrollbar样式功能
import "codemirror/addon/scroll/simplescrollbars.css";
import "codemirror/addon/scroll/simplescrollbars";
// #endregion

import $http from "../../utils/apiHelper";
import * as $base from "../../utils/js-base64/base64";
import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/base16-dark.css";
import "codemirror/mode/clike/clike.js";
export default {
  components: { codemirror },
  props: {},
  mounted() {
    this.loadFilter();
    this.getTaskHistory();
  },
  data() {
    return {
      multipleSelection: [],
      code: "",
      cmOptions: {
        // codemirror options
        tabSize: 4,
        mode: "text/x-csharp",
        lineNumbers: true,
        theme: "base16-dark",
        line: true,
        readOnly: true,
        // more codemirror options, 更多 codemirror 的高级配置...
      },
      triggerVisible: false,
      loading: false,
      ruleType: [
        { name: "全选", value: -1 },
        { name: "循环", value: 0 },
        { name: "调度", value: 1 },
        { name: "触发", value: 2 },
      ],
      stateType: [
        { name: "全选", value: -1 },
        // { name: "未发布保存", value: 0 },
        { name: "生效", value: 0 },
        { name: "暂停", value: 1 },
        { name: "结束", value: 2 },
      ],
      lineType: [],
      processType: [],
      eqType: [],
      pageNum: 1,
      pageSize: 20,
      total: 1,
      tableData: [],
      rule: -1,
      state: -1,
      eqSearchName: "",
      lineName: "",
      processName: "",
      scriptName: "",
      scriptContent: "",
      sortMethod: "descending",

      searchConditionLast: {
        pageSize: 0,
        pageNum: 0,
        lineName: "",
        eqSearchName: "",
        ruleType: 0,
        scriptName: "",
        status: 0,
        sortMethod: "",
        processName: "",
      },
    };
  },
  watch: {},
  computed: {},
  methods: {
    table_index(index) {
      return (this.pageNum - 1) * this.pageSize + index + 1;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleLogSearch(index, data) {
      console.log(data);
      let params = {
        logtype: "设备管理",
        lineName: data.lineName,
        processName: data.processName,
        eqName: data.eqName,
        scriptName: data.scriptName,
      };
      console.log("params", params);
      this.$router.push({
        path: "/operation/logFile",
        query: params,
      });

      let route =   {
    path: '/operation/logFile',
    name: 'logFile',
    meta: {
      title: '日志文件'
    },
  };
      // selectMenu使我们在tab.js中定义的方法 用于添加进tab中tabList集合方法
      this.$store.commit("selectMenu", route);

    },
    ///排序
    handleSort(sort) {
      if (sort) {
        this.sortMethod = sort.order || "";
      }
      this.tableData = [];
      this.getTaskHistory();
      // 发送排序请求到后端
      // 接收排序数据并更新tableData
    },
    ///排序

    handleEdit(index, data) {
      if (data.scriptContentId) {
        $http
          .get(`/AcquisitionTask/GetContent?id=${data.scriptContentId}`)
          .then((res) => {
            if (res.Data && res.Data.length) {
              console.log(res.Data);

              console.log($base.Base64.decode(res.Data));
              this.scriptContent = $base.Base64.decode(res.Data);
              this.triggerVisible = true;
            } else {
              this.$message.error("查询脚本信息失败,脚本内容不存在");
            }
          });
      } else {
        this.$message.error("查询脚本信息失败,脚本ID不可为空");
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getTaskHistory();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getTaskHistory();
    },
    getTaskHistory() {
      this.loading = true;
      let param = {
        pageSize: this.pageSize,
        currentPage: this.pageNum,
        lineName: this.lineName,
        eqSearchName: this.eqSearchName,
        ruleType: this.rule,
        scriptName: this.scriptName,
        status: this.state,
        sortMethod: this.sortMethod,
        processName: this.processName,
      };

      let isDifferent = false;
      for (let key in param) {
        if (
          key !== "currentPage" &&
          JSON.stringify(param[key]) !==
            JSON.stringify(this.searchConditionLast[key])
        ) {
          isDifferent = true;
          break;
        }
      }

      if (isDifferent) {
        this.pageNum = 1;
        param.currentPage = 1;
      }

      this.searchConditionLast = param;

      $http
        .post("/AcquisitionTask/GetAcquisitionTask", param)
        .then((res) => {
          if (res.Data && res.Data.length) {
            this.tableData = res.Data;
            this.total = res.Data[0].totalCount;
          } else {
            this.tableData = [];
            this.total = 1;
          }

          this.loading = false;
        })
        .catch((error) => {
          console.error(error);
          this.loading = false;
        });
    },

    loadFilter() {
      $http
        .get("/Log/GetOptionValue")
        .then((res) => {
          if (res && res.message == null) {
            let arr = [...res.Data];
            this.lineType = arr.filter(
              (e) => e.optionsName == "lineOptions"
            )[0].options;
            this.processType = arr.filter(
              (e) => e.optionsName == "procOptions"
            )[0].options;
          }
        })
        .catch((err) => {
          console.error("GetOptionValue", err);
        });
    },

    handleSingleStateChange(index, data, buttonText) {
      this.$confirm("确定" + buttonText + "该任务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let param = {
          IdList: [],
          Status: buttonText == "启动执行" ? 0 : 1,
        };
        param.IdList.push(data.scriptId);
        this.changeExcuteState(param);
      });
    },

    handleStateListChange(buttonText) {
      this.$confirm("确定" + buttonText + "这些任务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let param = {
          IdList: [],
          Status: buttonText == "启动执行" ? 0 : 1,
        };
        if(this.multipleSelection.length == 0)
        {
          this.$message({
              type: "error",
              message: "批量操作失败！请至少选择一个脚本!",
            });
            return;
        }

        this.multipleSelection.forEach((element) => {
          param.IdList.push(element.scriptId);
        });
        this.changeExcuteState(param);
      });
    },

    changeExcuteState(param) {
      this.loading = true;

      $http
        .post("/AcquisitionTask/SetScripStatus", param)
        .then((res) => {
          if (res.Data) {
            this.$message({
              type: "success",
              message: "状态更改成功!",
            });
          } else {
            this.$message({
              type: "error",
              message: "状态更改失败!",
            });
          }
          this.loading = false;
          this.getTaskHistory();
        })
        .catch((error) => {
          this.$message({
            type: "error",
            message: error,
          });
          console.error(error);
          this.getTaskHistory();
          this.loading = false;
        });
    },
  },
  created() {},
};
</script>
<style scoped>
.CodeMirror-scrollbar-handle {
  width: 10px;
}

::v-deep .CodeMirror-hscrollbar {
  background-color: red !important;
}

::v-deep .CodeMirror-vscrollbar {
  background-color: red !important;
}

::v-deep .CodeMirror {
  height: 600px;
}
</style>
